package lingou.homework.postbar.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import lingou.homework.postbar.controller.tool.LogPrinter;
import lingou.homework.postbar.controller.tool.SessionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Date;

@Component
public class LogInterceptor implements HandlerInterceptor {
    @Autowired
    LogPrinter logPrinter;
    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        synchronized (this){
            logPrinter.println(
                    new Date(System.currentTimeMillis()),
                    request.getMethod(),
                    request.getRequestURL(),
                    "UserId:", SessionHelper.getCurrentUser(request.getSession()),
                    "Session:", request.getSession().getId());

            logPrinter.print("Headers: {");
            request.getHeaderNames().asIterator().forEachRemaining(x ->{
                logPrinter.print(x + ": " + request.getHeader(x) + ";");
            });
            logPrinter.printlnDepth(1, "}");

            request.getParameterMap().forEach((k, v) -> {
                if(v.length == 1) logPrinter.printlnDepth(2, k + ": " + v[0]);
                else logPrinter.printlnDepth(2, k + ": " + Arrays.toString(v));
            });
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//        logPrinter.printlnDepth(1, "Response:", response.getStatus());
    }
}
